package com.ruoyi.draw.util;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.draw.config.ServerConfigs;
import com.ruoyi.draw.domain.ModelConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.Base64;

/**
 * 图像生成工具类 - 统一文件保存路径（与 RuoYi 上传一致）
 */
@Component
public class IMGuse {

    private final RestTemplate restTemplate = new RestTemplate();

    @Autowired
    private RuoYiConfig ruoYiConfig;

    @Autowired
    private ServerConfigs serverConfig;

    /**
     * 生成图像（prompt-only）
     */
    public String generateImage(ModelConfig modelConfig, String prompt) {
        String apiUrl = modelConfig.getBaseUrl();
        String apiKey = modelConfig.getApiKey();
        String model = modelConfig.getModel();

        System.out.println("=== 🧩 调试信息 ===");
        System.out.println("模型名称: " + model);
        System.out.println("请求地址: " + apiUrl);
        System.out.println("Prompt内容: " + prompt);
        System.out.println("===================");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (apiKey != null && !apiKey.isEmpty()) headers.setBearerAuth(apiKey);

        JSONObject body = new JSONObject();
        body.put("model", model);
        body.put("prompt", prompt);
        body.put("cfg", 7.8);
        body.put("num_inference_steps", 50);

        HttpEntity<String> entity = new HttpEntity<>(body.toJSONString(), headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, entity, String.class);
            System.out.println("📥 HTTP状态码：" + response.getStatusCode());
            System.out.println("📥 响应内容：" + response.getBody());

            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject res = JSONObject.parseObject(response.getBody());
                JSONArray images = res.getJSONArray("images");

                if (images != null && !images.isEmpty()) {
                    JSONObject img = images.getJSONObject(0);
                    String base64 = null;

                    if (img.containsKey("b64_json")) {
                        base64 = img.getString("b64_json");
                    } else if (img.containsKey("url")) {
                        return img.getString("url");
                    }

                    if (base64 != null) {
                        // ✅ 保存图片文件到统一目录
                        return saveBase64Image(base64);
                    }
                }
            }
            return "生成失败：" + response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return "图像生成异常：" + e.getMessage();
        }
    }

    /**
     * 生成图像（带参考图）
     */
    public String generateImageWithReferences(ModelConfig modelConfig, String prompt,
                                              String image, String image2, String image3) {
        String apiUrl = modelConfig.getBaseUrl();
        String apiKey = modelConfig.getApiKey();
        String model = modelConfig.getModel();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (apiKey != null && !apiKey.isEmpty()) headers.setBearerAuth(apiKey);

        JSONObject body = new JSONObject();
        body.put("model", model);
        body.put("prompt", prompt);
        body.put("cfg", 7.8);
        body.put("num_inference_steps", 50);

        try {
            if (image != null && !image.isEmpty()) body.put("image", toBase64IfFile(image));
            if (model != null && model.toLowerCase().contains("edit")) {
                if (image2 != null && !image2.isEmpty()) body.put("image2", toBase64IfFile(image2));
                if (image3 != null && !image3.isEmpty()) body.put("image3", toBase64IfFile(image3));
            }
        } catch (IOException e) {
            return "❌ 参考图转换失败：" + e.getMessage();
        }

        HttpEntity<String> entity = new HttpEntity<>(body.toJSONString(), headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, entity, String.class);
            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject res = JSONObject.parseObject(response.getBody());
                JSONArray images = res.getJSONArray("images");
                if (images != null && !images.isEmpty()) {
                    JSONObject img = images.getJSONObject(0);
                    String base64 = null;

                    if (img.containsKey("b64_json")) {
                        base64 = img.getString("b64_json");
                    } else if (img.containsKey("url")) {
                        return img.getString("url");
                    }

                    if (base64 != null) {
                        return saveBase64Image(base64);
                    }
                }
            }
            return "生成失败：" + response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return "图像生成异常：" + e.getMessage();
        }
    }

    /**
     * ✅ 将生成的 Base64 图片保存到与 upload 相同目录
     */
    private String saveBase64Image(String base64Data) throws IOException {
        // 去掉前缀
        if (base64Data.startsWith("data:image")) {
            base64Data = base64Data.substring(base64Data.indexOf(",") + 1);
        }

        byte[] bytes = Base64.getDecoder().decode(base64Data);

        String uploadPath = RuoYiConfig.getUploadPath();
        String datePath = DateUtils.datePath();
        String fileName = IdUtils.fastSimpleUUID() + ".png";

        Path dirPath = Paths.get(uploadPath, datePath);
        if (!Files.exists(dirPath)) {
            Files.createDirectories(dirPath);
        }

        Path fullPath = dirPath.resolve(fileName);
        Files.write(fullPath, bytes, StandardOpenOption.CREATE);

        // ✅ 生成统一访问路径
        String relativePath = Constants.RESOURCE_PREFIX + "/" + datePath + "/" + fileName;
        String url = serverConfig.getUrl() + relativePath;

        System.out.println("✅ 图片已保存：" + fullPath);
        System.out.println("🌐 访问URL：" + url);

        return url;
    }

    /**
     * 转 Base64（支持 file path）
     */
    private String toBase64IfFile(String input) throws IOException {
        if (input == null || input.isEmpty()) return input;

        if (input.startsWith("http://") || input.startsWith("https://") || input.startsWith("data:image")) {
            return input;
        }

        String basePath = ruoYiConfig.getProfile();
        String cleanedInput = input.replaceFirst("^[\\/]+", "").replaceFirst("^(?i)profile[/\\\\]", "");
        Path fullPath = Paths.get(basePath, cleanedInput);

        if (Files.isRegularFile(fullPath)) {
            byte[] bytes = Files.readAllBytes(fullPath);
            return "data:image/png;base64," + Base64.getEncoder().encodeToString(bytes);
        } else {
            return input;
        }
    }
}
